package routers

import (
	"encoding/json"
	"net/http"
	"strconv"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/popedom"

	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

//ExportXlsxRouter 导出数据到xlsx
func ExportXlsxRouter(c echo.Context) error {
	daoName := c.Param("DaoName")
	if daoName == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "daoName不能为空！")
	}
	var whereCauses []base.WhereCause
	jsonStr := c.FormValue("WhereCauses")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &whereCauses)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	var columnHeaders []base.ColumnHeader
	jsonStr = c.FormValue("ColumnHeaders")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &columnHeaders)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	var orderItems []base.OrderItem
	jsonStr = c.FormValue("OrderItems")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &orderItems)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	dao, err := base.GetDao(daoName)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	permIDStr := c.FormValue("PermID")
	if permIDStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "PermID不能为空！")
	}
	permID, err := strconv.Atoi(permIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "PermID必须为整数！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	pTypes, err := popedom.GetUserPermissionTypes(claims.UserID, permID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	xlsx := base.NewXlsx(dao, whereCauses, orderItems, columnHeaders)
	buff, err := xlsx.Export(claims.UserID, pTypes...)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	c.Response().Header().Set("Content-Type", "application/vnd.ms-excel")
	return c.Blob(http.StatusOK, "application/vnd.ms-excel", buff.Bytes())
}
